package nl.fotoniq.android.lockpicker.shared;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.provider.Settings;

/**
 * The Class LockPickerActivity.
 * <p>
 * The main activity.
 * </p>
 * 
 * @author jeroen.brosens
 */
public class LockPickerActivity extends PreferenceActivity implements OnPreferenceChangeListener {

	private boolean isServiceExpectedRunning;
	private boolean isShowingNotifications;

	private Intent lockPickerServiceIntent;

	private CheckBoxPreference prefServiceState;
	private CheckBoxPreference prefShowNotifications;
	private Preference prefVersionCode;

	private String keyDisclaimerAccepted;
	private String keyServiceState;
	private String keyShowNotifications;
	private String keyVersionCode;

	private SharedPreferences preferences;

	/**
	 * {@inheritDoc}
	 * 
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.preferences);

		keyDisclaimerAccepted = getString(R.string.pref_disclaimer_accepted_key);
		keyServiceState = getString(R.string.pref_service_key);
		keyShowNotifications = getString(R.string.pref_show_notifications_key);
		keyVersionCode = getString(R.string.pref_version_key);

		getPreferenceManager().setSharedPreferencesName(LockPickerConstants.PREFERENCES_NAME);
		preferences = getPreferences(Context.MODE_PRIVATE);

		prefServiceState = (CheckBoxPreference) findPreference(keyServiceState);
		prefServiceState.setOnPreferenceChangeListener(this);

		prefShowNotifications = (CheckBoxPreference) findPreference(keyShowNotifications);
		prefShowNotifications.setOnPreferenceChangeListener(this);

		prefVersionCode = findPreference(keyVersionCode);
		showApplicationVersion();

		lockPickerServiceIntent = new Intent(this, LockPickerService.class);

		LockPickerUtil.log_d("LockPicker activity created");
	}

	private void showApplicationVersion() {
		prefVersionCode.setSummary(LockPickerUtil.getApplicationVersionName(this));
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();

		init();
	}

	private void init() {
		if (isDisclaimerAccepted()) {
			if (LockPickerUtil.isLockSettingPresent(this)) {
				if (!prefServiceState.isEnabled()) {
					prefServiceState.setEnabled(true);
				}

				isServiceExpectedRunning = preferences.getBoolean(keyServiceState,
						LockPickerConstants.DEFAULT_SERVICE_STARTED);
				prefServiceState.setChecked(isServiceExpectedRunning);
			} else {
				prefServiceState.setChecked(false);
				prefServiceState.setEnabled(false);

				showSyncSettingsDialog();
			}
			updateServiceState();

			if (!prefShowNotifications.isEnabled()) {
				prefShowNotifications.setEnabled(true);
			}

			isShowingNotifications = preferences.getBoolean(keyShowNotifications,
					LockPickerConstants.DEFAULT_SHOW_NOTIFICATIONS);
			prefShowNotifications.setChecked(isShowingNotifications);
		} else {
			isServiceExpectedRunning = LockPickerConstants.DEFAULT_SERVICE_STARTED;
			prefServiceState.setChecked(isServiceExpectedRunning);

			updateServiceState();
			showDisclaimerDialog();
		}
	}
	
	private boolean isDisclaimerAccepted() {
		if (preferences.getBoolean(getString(R.string.pref_disclaimer_accepted_key),
				LockPickerConstants.DEFAULT_DISCLAIMER_ACCEPTED)) {
			LockPickerUtil.log_d("Disclaimer accepted");

			return true;
		} else {
			LockPickerUtil.log_d("Disclaimer not accepted yet");

			return false;
		}
	}

	private void showDisclaimerDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(false);
		builder.setTitle(R.string.disclaimer_title);
		builder.setMessage(getString(R.string.disclaimer_text));

		builder.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				SharedPreferences.Editor editor = preferences.edit();
				editor.putBoolean(keyDisclaimerAccepted, true);
				editor.commit();

				LockPickerUtil.log_d("Disclaimer accepted; saved");

				dialog.dismiss();
				LockPickerActivity.this.init();
			}
		});

		builder.setNegativeButton(getString(R.string.decline), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
				LockPickerActivity.this.finish();
			}
		});

		AlertDialog dialog = builder.create();
		LockPickerUtil.blurAndDimBackground(dialog);

		dialog.show();
	}

	private void showSyncSettingsDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setTitle(R.string.setup_sync_title);
		builder.setMessage(getString(R.string.setup_sync_text));

		builder.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				LockPickerUtil.log_d("Showing sync settings");

				// Go to applicable Android system settings
				Intent syncIntent = new Intent(Settings.ACTION_SYNC_SETTINGS);
				startActivity(syncIntent);

				dialog.dismiss();
			}
		});

		builder.setNegativeButton(getString(R.string.decline), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});

		AlertDialog dialog = builder.create();
		LockPickerUtil.blurAndDimBackground(dialog);

		dialog.show();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see android.preference.Preference.OnPreferenceChangeListener#onPreferenceChange(android.preference.Preference,
	 *      java.lang.Object)
	 */
	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		LockPickerUtil.log_d("Preference changed");

		SharedPreferences.Editor editor = preferences.edit();

		if (preference.getKey().equals(keyServiceState)) {
			isServiceExpectedRunning = !prefServiceState.isChecked();

			updateServiceState();

			editor.putBoolean(keyServiceState, isServiceExpectedRunning);
		} else if (preference.getKey().equals(keyShowNotifications)) {
			isShowingNotifications = !prefShowNotifications.isChecked();
			editor.putBoolean(keyShowNotifications, isShowingNotifications);

			if (!isShowingNotifications) {
				LockPickerNotifier.cancelNotification(this);
			}
		}

		return editor.commit();
	}

	private void updateServiceState() {
		LockPickerUtil.log_d("Updating service running state to: " + isServiceExpectedRunning);

		if (isServiceExpectedRunning) {
			startService();
		} else {
			stopService();
		}
	}

	private boolean startService() {
		LockPickerUtil.log_d("Attempting to start service...");

		if (!LockPickerUtil.isServiceRunning(this)) {
			ComponentName service = startService(lockPickerServiceIntent);
			if (service == null) {
				LockPickerUtil.log_e("Error starting service", null);
				LockPickerNotifier.showToast(this, R.string.error_starting_service);

				return false;
			}
			LockPickerUtil.log_d("Service started successfully");
			LockPickerNotifier.showToast(this, R.string.service_started);
		} else {
			LockPickerUtil.log_d("Service already started");
		}
		return true;
	}

	private boolean stopService() {
		LockPickerUtil.log_d("Attempting to stop service...");

		if (LockPickerUtil.isServiceRunning(this)) {
			if (stopService(lockPickerServiceIntent)) {
				LockPickerUtil.log_d("Service stopped successfully");
				LockPickerNotifier.showToast(this, R.string.service_stopped);

				return true;
			}
			LockPickerUtil.log_e("Error stopping service", null);
			LockPickerNotifier.showToast(this, R.string.error_stopping_service);
		} else {
			LockPickerUtil.log_d("Service already stopped");
		}
		return false;
	}
}